#include <iostream>
#include <string>
#include <memory>
#include <ctime>
#include "InetAddr.hpp"
#include "Socket.hpp"
#include "Protocol.hpp"
using namespace std;
using namespace socket_ns;
using namespace protocol_ns;
void Usage(string proc)
{
    cout << "Usage:" << proc << "server-ip server-port" << endl;
}

int main(int argc, char *argv[])
{
    // ./TcpClient ip port
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(-1);
    }
    string serverip = argv[1];           // ip地址
    uint16_t serverport = stoi(argv[2]); // 字符串转换整形，拿到端口号

    unique_ptr<Socket> cli = make_unique<TcpSocket>();

    InetAddr serveraddr(serverip, serverport);
    bool res = cli->BulidClientSocket(serveraddr);
    Factory factory;
    string inbuffer;
    cout << "res:" << res << endl;
    while (res == true)
    {
        sleep(1);
        //  连接服务器成功
        string str;
        for (int i = 0; i < 5; i++)
        {
            //  1.构建一个请求
            auto req = factory.BulidRequest();

            // 2。对请求做序列化
            string send_ptr;
            req->Serialize(&send_ptr);
            cout << "客户端序列化结束：" << send_ptr << endl;

            // 3.添加长度报头
            send_ptr = Encode(send_ptr);
            cout << "客户端添加报头结束：" << send_ptr << endl;
            str += send_ptr;
        }
        // 4.发送数据给服务器
        cli->Send(str);
        cout << "发送成功" << endl;

        // 5.读取服务器反馈的数据
        int n = cli->Recv(&inbuffer);
        if (n <= 0)
        {
            break;
        }
        cout << "客户端读取到的信息：" << inbuffer << endl;

        // 6.对读取到的信息做检测
        string package = Decode(inbuffer); // 拿到"len"\r\n"{   }"\r\n有效信息
        if (package.empty() == true)
        {
            continue;
        }
        cout << "获取到序列化信息：" << package << endl;

        // 7.构建响应对象
        auto resp = factory.BulidResponse();

        // 8.反序列化
        resp->UnSerialize(package);

        // 打印数据
        cout << "结果:" << resp->_result << " [" << resp->_code << "]" << endl;
    }
}
